﻿using GameServer.Network;
using Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf;

namespace GameServer
{
    internal class NetService 
    {
        TcpSocketListener listener = null;
        public NetService()
        {
        }

        public void Init(int port)
        {
            listener = new TcpSocketListener("0.0.0.0", port);
            listener.SocketConnected += OnClientConnect;
        }

        public void Start()
        {
            listener.Start();
        }

        private void OnClientConnect(object? sender, Socket socket)
        {
            // 接入客户端
            var ipe = socket.RemoteEndPoint as System.Net.IPEndPoint; // 客户端的ip和端口 (向下转型)
            Console.WriteLine("有客户端连入: IP: " + ipe.Address + "  " + "Port:" + ipe.Port);

            NetConnection netConnection = new NetConnection(socket, 
               new NetConnection.DataReceivedCallback(OnDataRecived),
               new NetConnection.DisconnectedCallback(OnDisConnected)
                );
   
        }

        private void OnDataRecived(NetConnection sender, byte[] data)
        {
            Package v = Package.Parser.ParseFrom(data);
  
            // 将消息放入消息队列
            MessageRounter.Instance.AddMessage(sender, v);

            Console.WriteLine(MessageRounter.Instance.messageQueue.Count);
        }

        private void OnDisConnected(NetConnection sender)
        {
            Console.WriteLine("有客户端断开连接");
        }





    }
}
